package com.talent.web.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.talent.web.enums.PermissionType;
import com.talent.web.enums.ResponseEnum;
import com.talent.web.exception.TalentException;
import com.talent.web.mapper.SysUserMapper;
import com.talent.web.model.convertor.UserConvertor;
import com.talent.web.model.dto.AllocationRoleDto;
import com.talent.web.model.dto.SysUserDto;
import com.talent.web.model.entity.SysMenu;
import com.talent.web.model.entity.SysUser;
import com.talent.web.model.query.UserQuery;
import com.talent.web.model.vo.SysUserVo;
import com.talent.web.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName：ResponseEnum
 * @Author: hszhou
 * @Date: 2024/10/21 13:35
 * @Description: 用户接口实现
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {




    private Logger logger = LoggerFactory.getLogger(getClass());



    @Override
    public SysUser selectUserByUsername(String username) {
        LambdaQueryWrapper<SysUser> eq = new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username);
        return this.baseMapper.selectOne(eq);
    }

    @Override
    public SysUser selectUserByMobile(String phone) {
        LambdaQueryWrapper<SysUser> eq = new LambdaQueryWrapper<SysUser>().eq(SysUser::getMobile, phone);
        return this.baseMapper.selectOne(eq);
    }

    @Override
    public IPage<SysUserVo> page(int current, int pageSize, UserQuery query) {
     IPage<SysUserVo> page = new Page<>(current,pageSize);
        return  this.baseMapper.page(page,query);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSysUser(SysUserDto dto) {
        SysUser sysUser = UserConvertor.INSTANCE.dtoTPo(dto);
        sysUser.setPassword("111");
        this.baseMapper.insert(sysUser);
        Long userId = sysUser.getId();
        List<String> roleIds = dto.getRoleIds();
        AllocationRoleDto allocationRoleDto = new AllocationRoleDto();
        allocationRoleDto.setUserId(userId);
        allocationRoleDto.setRoleIds(roleIds);
        allocationRole(allocationRoleDto);
    }

    @Override
    public void deleteById(String id) {
        this.baseMapper.deleteById(id);
    }

    @Override
    public void updateUser(SysUserDto dto) {

        SysUser user = this.baseMapper.selectById(dto.getId());
        if(user==null){
            throw new TalentException(ResponseEnum.DATA_NOT_FOUND);
        }

        List<String> roleIds = dto.getRoleIds();

        SysUser updateUser = UserConvertor.INSTANCE.update(dto, user);


        AllocationRoleDto allocationRoleDto = new AllocationRoleDto();
        allocationRoleDto.setUserId(dto.getId());
        allocationRoleDto.setRoleIds(roleIds);
        allocationRole(allocationRoleDto);

        this.baseMapper.updateById(updateUser);
    }

    @Override
    public void upgradePassword(String username, String newPassword) {
         this.baseMapper.upgradePassword(username,newPassword);
    }


    @Override
    public List<String> getPermission(Long userId) {

      return this.baseMapper.getPermissions(userId)
                .stream().filter(e->e.getType()== PermissionType.BUTTON.getCode())
                .map(SysMenu::getCode).collect(Collectors.toList());

    }

    @Override
    public void allocationRole(AllocationRoleDto dto) {

        Long userId = dto.getUserId();
        //查询用户已经有的角色
        List<String> hasRoleIds = this.baseMapper.hasRoleIds(userId).stream().map(Objects::toString).collect(Collectors.toList());
        ArrayList<String> copy = CollectionUtil.newArrayList(hasRoleIds);
        //获取新设置的角色
        List<String> roleIds = dto.getRoleIds();

        //需要删除的角色
        if(CollectionUtil.isNotEmpty(hasRoleIds)){
            hasRoleIds.removeAll(roleIds);
            if(CollectionUtil.isNotEmpty(hasRoleIds)){
                this.baseMapper.removeRoleByUserIdAndRoleIds(userId,hasRoleIds);
            }
        }
        roleIds.removeAll(copy);
        //需要新增的角色
        if(CollectionUtil.isNotEmpty(roleIds)){
            this.baseMapper.saveUserRole(roleIds,userId);
        }


    }

    @Override
    public SysUserVo detail(Long id) {
        SysUser sysUser = this.baseMapper.selectById(id);
        SysUserVo sysUserVo = UserConvertor.INSTANCE.poToVo(sysUser);
        //获取用户的角色
        List<String> roleIds = this.baseMapper.hasRoleIds(id)
                .stream().map(Object::toString).collect(Collectors.toList());
        sysUserVo.setRoleIds(roleIds);

        return sysUserVo;
    }
}
